/**
 * COPYRIGHT (C) 2009. Denny Tran, Omar Jaime, David Deng, Julie Hsieh. All Rights Reserved
 * The overall system of the scheduling system.  
 * @author Denny Tran, Omar Jaime, David Deng, Julie Hsieh 
 * @version 1.01 2009-05-05
 */

package data;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.URL;
import java.sql.SQLException;
import java.util.*;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;

import test.TestGroup;

import gui.ViewManager;


public class GroupSystem
{
    private User user;      // current user
    private Group group;    // current group
    private ViewManager viewMgr;
    private static MySqlConnection mySql;
    
    private GregorianCalendar startOfWeek;
    private GregorianCalendar endOfWeek;
    
    /**
     * Constructs a group system object and prompts user for login.
     * @throws SQLException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws ClassNotFoundException
     */
    public GroupSystem() throws SQLException, InstantiationException, 
    IllegalAccessException, ClassNotFoundException
    {
//        user = new User("Omar", "sucks", 2);
//        group = TestGroup.getFakeGroup();
       
       mySql = new MySqlConnection();
       login();   //sets user, group

    }
    
    /**
     * Prompts user for login.
     * @throws SQLException
     */
    public void login() throws SQLException
    {
//       String username = "jkhsieh";
//       String password = "mojito";
       
       String username = "";
       String password = "";
       
       boolean logged = false;
       UIManager.put("OptionPane.okButtonText", "Login");
       
       while(!logged)
       {
          JFrame loginFrame = new JFrame();
          
          //own panel
          JPanel picturePanel = new JPanel();
          JPanel userPanel = new JPanel();
          JPanel passPanel = new JPanel();

          //picture of logo
          URL imageURL = GroupSystem.class.getResource("mojito_transparent.png");
          picturePanel.add(new JLabel(new ImageIcon(imageURL)));
          
          //element's in panel
          JTextField userFields = new JTextField(9);
          JPasswordField passwordFields = new JPasswordField(9);

          userPanel.add(new JLabel("User Name:"));
          userPanel.add(userFields);
          passPanel.add(new JLabel("Password:"));
          passPanel.add(passwordFields);
          
          //array of object for the optionpane
          Object[] fields = {picturePanel, userPanel, passPanel};

          JOptionPane op = new JOptionPane(fields,
                               JOptionPane.PLAIN_MESSAGE,
                               JOptionPane.DEFAULT_OPTION,
                               null, null);

          JDialog dialog = op.createDialog(loginFrame, "Login");
          dialog.setVisible(true);
          dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

          int result = -1;

          try
          {
              result = ((Integer)op.getValue()).intValue();
          }
          catch(Exception uninitializedValue)
          {}

          if(result == JOptionPane.OK_OPTION)
          {
             username = userFields.getText();
             password = passwordFields.getText();
             
             System.out.println("Login info: " + username + ", " + password);
          }
          else
          {
              System.out.println("Closed System");
              System.exit(0);
          }
          
          user = mySql.getUser(username, password);
          
          if(user != null) 
             logged = true;
          else
             JOptionPane.showMessageDialog(null, "Incorrect login name and password!");
       }
       
       UIManager.put("OptionPane.okButtonText", "Ok");
       
       group = mySql.getGroup(user);
       
       //update current user
       ArrayList<User> users = group.getUsers();
       
       ArrayList<Event> events = mySql.getUserEvents("");
       MyCalendar cal = new MyCalendar(events);
       group.setGroupCalendar(cal);
       
       for(User u: users)
       {
          events = mySql.getUserEvents(u.getUserName());
          cal = new MyCalendar(events);
          u.setUserCalendar(cal);
          if(u.getUserName().equals(username)) user = u;
       }

       //get week's events for each group user...
       
       //calculate Sunday and Saturday dates for query
//       startOfWeek = new GregorianCalendar();                //first guess
//       int weekday = startOfWeek.get(Calendar.DAY_OF_WEEK);  //0=SUNDAY
//       int daysFromSun = Calendar.SUNDAY - weekday;     // <= 0, i.e. negative
//       
//       startOfWeek.add(Calendar.DAY_OF_YEAR, daysFromSun);   //Sunday date adjusted
//       startOfWeek.set(Calendar.HOUR_OF_DAY, 0);
//       startOfWeek.set(Calendar.MINUTE, 0);
//       
//       endOfWeek = (GregorianCalendar) startOfWeek.clone();
//       endOfWeek.add(Calendar.DAY_OF_YEAR, 7);               //Saturday date adjusted
//       endOfWeek.set(Calendar.HOUR_OF_DAY, 0);
//       endOfWeek.set(Calendar.MINUTE, 0);
//       
//       setCalendars();

       viewMgr = new ViewManager(this);
    }
    
    
    /**
     * Initializes group and user calendars.
     * @throws SQLException
     */
    private void setCalendars() throws SQLException
    {
       String startStamp = TwoPlaceString.getSqlTimestamp(startOfWeek);
       String endStamp = TwoPlaceString.getSqlTimestamp(endOfWeek);
       
       group.setGroupCalendar(new MyCalendar(
             mySql.getEvents(group.getGroupID(), startStamp, endStamp) ));
       
       ArrayList<User> members = group.getUsers();
       for(User u : members)
       {
          u.setUserCalendar(new MyCalendar(
                mySql.getEvents(u.getUserName(), startStamp, endStamp) ));
       }
    }
    
    
    /**
     * Go back a week in the calendar.
     * @throws SQLException
     */
    public void backAWeek() throws SQLException
    {
       startOfWeek.add(Calendar.DAY_OF_YEAR, -7);
       endOfWeek.add(Calendar.DAY_OF_YEAR, -7);
       setCalendars();
    }
    
    /**
     * Go forward a week in the calendar.
     * @throws SQLException
     */
    public void forwardAWeek() throws SQLException
    {
       startOfWeek.add(Calendar.DAY_OF_YEAR, 7);
       endOfWeek.add(Calendar.DAY_OF_YEAR, 7);
       setCalendars();
    }
    
    
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException 
    {
       GroupSystem gs = new GroupSystem();
       
       //get username and password from login GUI, etc.
       //gs.login();
//     String username = "jkhsieh";
//     String password = "mojito";
       
       //print group name & calendar
       System.out.println("Group = " + gs.group.getGroupName());
       System.out.println("group cal: " + gs.group.getGroupCalendar().getNoOfEvents());
       
       System.out.println("Current User = " + gs.user.getRealName());
       System.out.println(" cal: " + gs.user.getUserCalendar().getNoOfEvents());
       
       //print users and calendars
       ArrayList<User> members = gs.group.getUsers();
       for(User u : members)
       {
          System.out.println(u);
          System.out.println(u.getUserName() + "'s events = " + u.getUserCalendar().getNoOfEvents());
          
          if(u.getUserCalendar().getNoOfEvents() != 0)
             System.out.println(u.getUserCalendar());
       }
       
//       //testing adding an event
//       String name = "Picnic";
//       String desc = "Going to the Picnic";
//       String type = "event";
//       GregorianCalendar start = new GregorianCalendar(2009, 4, 5, 13, 30);
//       GregorianCalendar end = new GregorianCalendar(2009, 4, 5, 15, 30);
//       
//       Event e1 = new Event(111, name, 0, "ddeng",type, start, end, desc);
//       
//       mySql.updateEvent(23, e1);
       
//       for(int i = 24; i<29; i++)
//          mySql.removeEvent(i);

       System.out.println("Done");
       
    }

    /**
     * Gets the current user of this system.
     * @return The current user of this system.
     */
    public User getUser()
    {
        return user;
    }

    /**
     * Sets the current user of this system.
     * @param user The user to set as the current user of this system.
     */
    public void setUser(User user)
    {
        this.user = user;
    }

    /**
     * Gets the group of this system.
     * @return The group of this system.
     */
    public Group getGroup()
    {
        return group;
    }

    /**
     * Sets the group of this system.
     * @param group The group to set this system to.
     */
    public void setGroup(Group group)
    {
        this.group = group;
    }

    /**
     * Gets the viewManager of this system.
     * @return The view manager of this system.
     */
    public ViewManager getViewMgr()
    {
        return viewMgr;
    }

    /**
     * Sets the view manager of this system.
     * @param viewMgr The view manager to set for this system.
     */
    public void setViewMgr(ViewManager viewMgr)
    {
        this.viewMgr = viewMgr;
    }

    /**
     * Gets the sql connection of this system.
     * @return The sql conneciton of this system.
     */
    public static MySqlConnection getMySql()
    {
        return mySql;
    }

    /**
     * Sets the sql connector of this system.
     * @param mySql The sql to connect to this system.
     */
    public static void setMySql(MySqlConnection mySql)
    {
        GroupSystem.mySql = mySql;
    }

    String[][] loginInfo = {{"kai", "password"},
                            {"deny", "password"},
                            {"omar", "admin"}
                           };
    
    public GroupSystem(String guiTester)
    {
        group = TestGroup.getFakeGroup();
        fakelogin();
        //user = group.getUsers().get(0);
        viewMgr = new ViewManager(this);
    }
    
    public void fakelogin()
    {
       String username = "";
       String password = "";
       
       boolean logged = false;
       UIManager.put("OptionPane.okButtonText", "Login");
       
       while(!logged)
       {
          JFrame loginFrame = new JFrame();
          
          //own panel
          JPanel picturePanel = new JPanel();
          JPanel userPanel = new JPanel();
          JPanel passPanel = new JPanel();

//          ImageIcon mojito = new ImageIcon("C:\\Documents and Settings\\Dave\\Desktop\\mojito_transparent.png");
          URL imageURL = GroupSystem.class.getResource("mojito_transparent.png");
          picturePanel.add(new JLabel(new ImageIcon(imageURL)));
          
          //element's in panel
          JTextField userFields = new JTextField(9);
          JPasswordField passwordFields = new JPasswordField(9);

          userPanel.add(new JLabel("User Name:"));
          userPanel.add(userFields);
          passPanel.add(new JLabel("Password:"));
          passPanel.add(passwordFields);
          
          //array of object for the optionpane
          Object[] fields = {picturePanel, userPanel, passPanel};

          JOptionPane op = new JOptionPane(fields,
                               JOptionPane.PLAIN_MESSAGE,
                               JOptionPane.DEFAULT_OPTION,
                               null, null);

          JDialog dialog = op.createDialog(loginFrame, "Login");
          dialog.setVisible(true);
          //dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

          System.out.println("ok option = " + JOptionPane.OK_OPTION);
          
          dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
          
          //loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          int result = -1;

          try
          {
              result = ((Integer)op.getValue()).intValue();
          }
          catch(Exception uninitializedValue)
          {}

          if(result == JOptionPane.OK_OPTION)
          {
             username = userFields.getText();
             password = passwordFields.getText();
             
             System.out.println("Login info: " + username + ", "+ password);
          }
          else
          {
              System.out.println("Closed System");
              System.exit(0);
          }
          
          //check username and password
          user = null;
          for(int i = 0; i < loginInfo.length; i++)
             if(loginInfo[i][0].equals(username) &&
                loginInfo[i][1].equals(password))
             {
              //update current user
                ArrayList<User> users = group.getUsers();
                for(User u: users)
                   if(u.getUserName().equals(username)) user = u;
             }
             
          if(user != null) 
             logged = true;
          else
             JOptionPane.showMessageDialog(null, "Incorrect login name and password!");
       }
       
       UIManager.put("OptionPane.okButtonText", "OK");
    }
}
